<!DOCTYPE html>
<html>

<head>
    <title> State and Lifecycle </title>
    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script>

    <style>
        body {
            background-color: green;
        }

        /* .h1 {
            color: red;
        } */
    </style>
</head>

<body>
    <div id="root"></div>
</body>

</html>

<script type="text/babel">
    //  Make Clock Component as a class
    class Clock extends React.Component {
        constructor(props) {
            super(props);
            // The only place to assign this.state.
            this.state = { date: new Date() };
        }

        //  When : Clock output is inserted in the DOM
        componentDidMount() {
            this.timerID = setInterval(() => this.tick(), 1000);
        }
        //  When : Clock component is removed from the DOM
        componentWillUnmount() {
            clearInterval(this.timerID);
        }

        tick() {
            // Don't modify State directly.
            // Wrong : not re-render a component
            // this.state.date = new Date();

            // Right
            this.setState({
                date: new Date()
            });
        }

        render() {
            return (
                <div id="data">
                    <h1 >Hello World</h1>
                    <h2 >time is {this.state.date.toLocaleTimeString()}</h2>
                </div>
            );
        }
    }
    // TODO : 如何知道h1 只更新一次，h2每次都更新。
    ReactDOM.render(<Clock />, document.getElementById('root'));
</script>